package argo.hot100.stack;

import java.util.Collections;
import java.util.Stack;

/**
 * result error
 */
public class DecodeString {

    public String decodeString(String s) {
        StringBuilder res = new StringBuilder();
        Stack<String> strStack = new Stack<>();
        Stack<Integer> numStack = new Stack<>();
        Stack<String> strStackTmp = new Stack<>();

        StringBuilder num = new StringBuilder();
        StringBuilder str = new StringBuilder();

        int leftTgCnt = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num.append(c);
                if (str.length() > 0) {
                    strStack.push(str.toString());
                    str.delete(0, str.length());
                }
            } else if (Character.isAlphabetic(c)) {
                str.append(c);
            } else {
                if (c == '[') {
                    numStack.push(Integer.valueOf(num.toString()));
                    num.delete(0, num.length());
                    leftTgCnt++;
                } else if (c == ']') {

                    Integer repetNum = numStack.pop();

                    String stackStr = "";
                    if (!strStack.isEmpty() && leftTgCnt > 0) {

                        while (!strStack.isEmpty() && !strStack.peek().equals("[")) {
                            strStackTmp.push(strStack.pop());
                        }
                        if (!strStack.isEmpty()) {
                            strStack.pop();
                        }
                        while (!strStackTmp.isEmpty()) {
                            stackStr += strStackTmp.pop();
                        }
                    }
                    String strp = str.toString();
                    if (str.length() == 0) {
                        strp = stackStr;
                        stackStr = "";
                    }

                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < repetNum; j++) {
                        sb.append(strp);
                    }
                    str.delete(0, str.length());

                    strStack.push(stackStr + sb.toString());
                    leftTgCnt--;

                }
            }

        }
        for (int i = 0; i < strStack.toArray().length; i++) {
            res.append(strStack.get(i));
        }

        return res.toString() + str;

    }


    public static void main(String[] args) {
        System.out.println(new DecodeString().decodeString("3[a2[c]]"));
        System.out.println(new DecodeString().decodeString("2[abc]3[cd]ef"));
        System.out.println(new DecodeString().decodeString("3[a]2[bc]"));
        System.out.println(new DecodeString().decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
        System.out.println(new DecodeString().decodeString("4[2[jk]e1[f]]ef"));
    }
}
